import { Injectable, HttpException, HttpStatus, } from '@nestjs/common';
import { CreateArticleDto } from './dtos/create-article.dto';
import { UpdateArticleDto } from './dtos/update-article.dto';
import { InjectRepository, } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { Article } from '../../entities/article.entity'
import { User } from '../../entities/user.entity'
import { ArticleCover } from '../../entities/articleCover.entity'
import { ArticleMoment } from '../../entities/articleMoment.entity'
import { ArticleLike } from '../../entities/articleLike.entity'
import { ArticleCollect } from '../../entities/articleCollect.entity'

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private readonly articleRepository: Repository<Article>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(ArticleCover)
    private readonly articleCoverRepository: Repository<ArticleCover>,
    @InjectRepository(ArticleMoment)
    private readonly articleMomentRepository: Repository<ArticleMoment>,
    @InjectRepository(ArticleLike)
    private readonly articleLikeRepository: Repository<ArticleLike>,
    @InjectRepository(ArticleCollect)
    private readonly articleCollectRepository: Repository<ArticleCollect>
  ) { }

  async create(userId: string, createArticleDto: CreateArticleDto) {

    const article = new Article();

    article.title = createArticleDto.title
    article.content = createArticleDto.content
    article.topic_id = createArticleDto.topic_id
    article.status = 0
    article.author = await this.userRepository.findOne({ where: { id: userId } })

    console.log(createArticleDto)

    const res = await this.articleRepository.save(article)
    console.log(res)
    const covers = createArticleDto.covers
    console.log(covers)
    covers.forEach(url => {
      this.articleCoverRepository.save({
        url,
        article: res
      })
    })

    return res
  }

  async findAll(query) {
    const page = Number(query.page)
    const limit = Number(query.limit)
    const list = await this.articleRepository.find({
      skip: (page - 1) * limit,
      take: limit,
      relations: ['author', 'covers'],
      where: {
        status: 1
      },
      order: {
        createdAt: 'DESC'
      }
    })
    const total = await this.articleRepository.count({
      where: {
        status: 1
      }
    })

    // 查询所有评论
    const articleList = await Promise.all(
      list.map(async item => ({
        ...item,
        commentCount: await this.articleMomentRepository.count({
          where: {
            article: {
              article_id: item.article_id
            }
          }
        }),
        likeCount: await this.articleLikeRepository.count({
          where: {
            article: {
              article_id: item.article_id
            }
          }
        })
      }))
    )

    return {
      limit,
      page,
      list: articleList,
      total,
    }
    // return 
  }

  async findOne(userId: string, article_id: string) {
    const article = await this.articleRepository.createQueryBuilder('article')
      .leftJoinAndSelect('article.covers', 'cover')
      .leftJoinAndSelect('article.author', 'author')
      .where({
        article_id
      })
      .getOne()


    // 判断是否查询到文章
    if (!article) {
      throw new HttpException('文章不存在', HttpStatus.NOT_FOUND)
    }

    // 添加封面
    article.covers = article.covers.map(item => item.url) as any

    // 添加评论数
    article.commentCount = await this.articleMomentRepository.count({
      where: {
        article: {
          article_id
        }
      }
    })

    // 添加点赞数
    article.likeCount = await this.articleLikeRepository.count({
      where: {
        article: { article_id }
      }
    })

    // 添加收藏数
    article.collectCount = await this.articleCollectRepository.count({
      where: { article: { article_id } }
    })

    // 是否已点赞
    const articleLike = await this.articleLikeRepository.findOne({
      where: { article: { article_id }, user: { id: userId } }
    })
    article.isLike = articleLike ? true : false

    // 是否已收藏
    const articleCollect = await this.articleCollectRepository.findOne({
      where: { article: { article_id }, user: { id: userId } }
    })
    article.isCollect = articleCollect ? true : false

    return article



  }

  update(id: number, updateArticleDto: UpdateArticleDto) {
    return `This action updates a #${id} article`;
  }

  remove(id: number) {
    return `This action removes a #${id} article`;
  }

  async auditArticle(userId: string, article_id: string, status: number) {
    const article = await this.articleRepository.findOne({ where: { article_id } })
    if (article === null) {
      throw new HttpException('传入article_id不正确', HttpStatus.BAD_REQUEST)
    }

    // 审核状态中
    if (article.status !== 0) {
      throw new HttpException('该文章不属于审核状态中', HttpStatus.BAD_REQUEST)
    }

    article.status = status
    await this.articleRepository.save(article)

    return "更改成功"
  }
}
